﻿//  --------------------------------
//  Copyright (c) AW Systems, Inc. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.codeplex.com/SLAM/license
//  ---------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Slam.Configuration;
using Slam.Data;
using Microsoft.SharePoint;

namespace Slam.Logging
{
	public class SqlLogger : ILogger
	{
		#region Private State

		private IConfigurationManager _configuration;
		private SqlLogDataRepository _database;
		private static TraceSwitch _switch;

		#endregion

		#region Properties

		public TraceSwitch Switch
		{
			get
			{
				return _switch;
			}
		}

		#endregion

		#region Constructors

		public SqlLogger(IConfigurationManager configuration)
		{
			_configuration = configuration;

			SPSite site = null;
			if (SPContext.Current != null && SPContext.Current.Site != null)
			{
				site = SPContext.Current.Site;
			}

			DataMapping currentDataMapping = _configuration.DataMapping;
			if (site != null)
			{
				string siteCollection = site.ServerRelativeUrl.TrimStart('/');
				if (!String.IsNullOrEmpty(siteCollection) && _configuration.DataMappings.ContainsKey(siteCollection))
				{
					currentDataMapping = _configuration.DataMappings[siteCollection];
				}
			}

			string connectionString = "";
			if (currentDataMapping is XmlSqlDataMapping)
			{
				connectionString = ((XmlSqlDataMapping)currentDataMapping).GetConnectionString();
			}

			if (String.IsNullOrEmpty(connectionString))
			{
				connectionString = _configuration.GetSection<ConnectionStringSection>("ConnectionStrings").Default;
			}
			else
			{
				connectionString = _configuration.GetSection<ConnectionStringSection>("ConnectionStrings").GetConnectionString(connectionString);
			}

			_database = new SqlLogDataRepository(connectionString);
			try
			{
				if (!_database.VerifySchemaExists("SLAM"))
				{
					_database.CreateSchema("SLAM");
				}
			}
			catch { }

			if (_switch == null)
			{
				_switch = new TraceSwitch("SLAMLogger", "SLAM Logging Trace Switch", "1");

				if (!_database.VerifyMessageTableExists("SLAM"))
				{
					_database.CreateMessageTable("SLAM");
				}

				_database.LogMessage("SLAM", "Information", "Trace Level: " + _switch.Level.ToString());
			}
		}

		~SqlLogger()
		{
			_database.Dispose();
		}

		#endregion

		#region ILogger Members

		public void LogEvent(string eventName, string typeName, string message)
		{
			if (!_database.VerifyEventTableExists("SLAM"))
			{
				_database.CreateEventTable("SLAM");
			}

			_database.LogEvent("SLAM", eventName, typeName, message);
		}

		public void LogMessage(string messageType, string message)
		{
			if ((_switch.TraceError && messageType.ToLower() == "exception") || _switch.TraceInfo)
			{
				if (!_database.VerifyMessageTableExists("SLAM"))
				{
					_database.CreateMessageTable("SLAM");
				}

				_database.LogMessage("SLAM", messageType, message);

				if (messageType.Equals("Exception", StringComparison.OrdinalIgnoreCase) && SPContext.Current != null)
				{
					//ExceptionEmailer.Send(SPContext.Current.Web, )
				}
			}
		}

		#endregion
	}
}
